$(document).ready(function () {
  // 图片查看器功能
  const imageViewer = $(
    '<div class="image-viewer"><img src="" alt="大图"></div>',
  ).appendTo('body');

  $('.gallery-image').click(function () {
    const imgSrc = $(this).attr('src');
    imageViewer.find('img').attr('src', imgSrc);
    imageViewer.addClass('active');
  });

  imageViewer.click(function () {
    $(this).removeClass('active');
  });

  // 地图标记提示
  $('.map-marker').each(function () {
    const title = $(this).attr('title');
    const tooltip = $('<div class="tooltip"></div>').text(title);
    $(this).append(tooltip);
  });

  // 搜索功能
  $('#search-btn').click(function () {
    const searchText = $('#search-input').val().toLowerCase();
    $('.post-item').each(function () {
      const postContent = $(this).text().toLowerCase();
      if (postContent.includes(searchText)) {
        $(this).show();
      } else {
        $(this).hide();
      }
    });
  });

  // 回车触发搜索
  $('#search-input').keypress(function (e) {
    if (e.which === 13) {
      $('#search-btn').click();
    }
  });

  // 评论功能
  $('#commentForm').submit(function (e) {
    e.preventDefault();
    const name = $('#commenterName').val();
    const content = $('#commentContent').val();
    const date = new Date().toLocaleDateString();

    // 创建新评论
    const newComment = $(`
            <li class="comment">
                <div class="comment-header">
                    <span class="commenter-name">${name}</span>
                    <span class="comment-date">${date}</span>
                </div>
                <div class="comment-content">${content}</div>
            </li>
        `);

    // 添加到评论列表
    $('.comment-list').prepend(newComment);

    // 保存到localStorage
    const comments = JSON.parse(localStorage.getItem('travelComments') || '[]');
    comments.unshift({ name, content, date });
    localStorage.setItem('travelComments', JSON.stringify(comments));

    // 清空表单
    this.reset();
  });

  // 加载已有评论
  function loadComments() {
    const comments = JSON.parse(localStorage.getItem('travelComments') || '[]');
    const commentList = $('.comment-list');
    commentList.empty();

    comments.forEach((comment) => {
      const commentElement = $(`
                <li class="comment">
                    <div class="comment-header">
                        <span class="commenter-name">${comment.name}</span>
                        <span class="comment-date">${comment.date}</span>
                    </div>
                    <div class="comment-content">${comment.content}</div>
                </li>
            `);
      commentList.append(commentElement);
    });
  }

  loadComments();

  // 图片懒加载
  const lazyImages = document.querySelectorAll('.gallery-image');
  if (lazyImages && lazyImages.length > 0) {
    const imageObserver = new IntersectionObserver((entries, observer) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const img = entry.target;
          if (img && img.dataset && img.dataset.src) {
            img.src = img.dataset.src;
            observer.unobserve(img);
          }
        }
      });
    });

    lazyImages.forEach((img) => {
      if (img) {
        imageObserver.observe(img);
      }
    });
  }

  // 目的地推荐点击效果
  $('.destination-item').click(function () {
    const title = $(this).find('h4').text();
    const description = $(this).find('p').text();
    alert(`即将为您展示更多关于 ${title} 的信息：\n${description}`);
  });

  // 标签点击筛选
  $('.tag-item').click(function (e) {
    e.preventDefault();
    const tag = $(this).text().toLowerCase();
    $('.post-item').each(function () {
      const postTags = $(this)
        .find('.tag')
        .map(function () {
          return $(this).text().toLowerCase();
        })
        .get();

      if (postTags.includes(tag)) {
        $(this).show();
      } else {
        $(this).hide();
      }
    });
  });

  // 统计数据动画
  function animateStats() {
    $('.stat-value').each(function () {
      const $this = $(this);
      const finalValue = parseInt($this.text());
      $({ value: 0 }).animate(
        { value: finalValue },
        {
          duration: 2000,
          step: function () {
            $this.text(Math.floor(this.value));
          },
        },
      );
    });
  }

  // 当统计区域进入视口时触发动画
  const statsObserver = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        animateStats();
        statsObserver.unobserve(entry.target);
      }
    });
  });

  // 添加元素存在性检查
  const statsElement = $('.travel-stats')[0];
  if (statsElement) {
    statsObserver.observe(statsElement);
  }
});
